package com.leo.apptest.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.leo.apptest.R;
import com.leo.apptest.service.MyService;

public class ServiceTestActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "ServiceTestActivity";
    private Button mBtStart;
    private Button mBtStop;
    private Button mBtBind;
    private Button mBtUnBind;
    private MyService.MyBinder myBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_test);
        mBtStart = (Button) findViewById(R.id.btStart);
        mBtStop = (Button) findViewById(R.id.btStop);
        mBtBind = (Button) findViewById(R.id.btBind);
        mBtUnBind = (Button) findViewById(R.id.btUnBind);

        mBtStart.setOnClickListener(this);
        mBtStop.setOnClickListener(this);
        mBtBind.setOnClickListener(this);
        mBtUnBind.setOnClickListener(this);

        Log.d(TAG, "onCreate: mainActivity thread "+Thread.currentThread().getId());
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyService.MyBinder) service;
            myBinder.startDownload();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: ");
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btStart:
                Intent startIntent = new Intent(this, MyService.class);
                startService(startIntent);
                break;
            case R.id.btStop:
                Intent stopIntent = new Intent(this,MyService.class);
                stopService(stopIntent);
                break;
            case R.id.btBind:
                Intent bindIntent = new Intent(this,MyService.class);
                bindService(bindIntent,connection,BIND_AUTO_CREATE);
                break;
            case R.id.btUnBind:
                unbindService(connection);
                break;
        }
    }
}
